const pool = require('../config/db');

const getCoupons = async () => {
    const [rows] = await pool.execute(`
        SELECT c.*, s.name as store_name, s.logo as store_logo
        FROM coupons c
        LEFT JOIN stores s ON c.store_id = s.id
        WHERE c.expire_date > NOW()
        ORDER BY c.created_at DESC
    `);
    return rows;
};

const checkCouponAvailability = async (couponId) => {
    const [rows] = await pool.execute(`
        SELECT * FROM coupons
        WHERE id = ? AND expire_date > NOW()
    `, [couponId]);

    return rows.length > 0;
};

const receiveCouponById = async (userId, couponId) => {
    const [result] = await pool.execute(`
        INSERT INTO user_coupons (user_id, coupon_id, receive_time, status)
        VALUES (?, ?, NOW(), 'unused')
    `, [userId, couponId]);

    return result;
};

const markCouponAsUsed = async (userId, userCouponId, orderId) => {
    const [result] = await pool.execute(`
        UPDATE user_coupons
        SET status = 'used', use_time = NOW(), order_id = ?
        WHERE id = ? AND user_id = ? AND status = 'unused'
    `, [orderId, userCouponId, userId]);

    return result;
};

module.exports = { getCoupons, checkCouponAvailability, receiveCouponById, markCouponAsUsed }; 